package com.example.java_gobang.api;


import com.example.java_gobang.game.Match;
import com.example.java_gobang.game.OnlineUserManager;
import com.example.java_gobang.game.RoomManager;
import com.example.java_gobang.model.MatchRequest;
import com.example.java_gobang.model.MatchResponse;
import com.example.java_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.regex.Matcher;

@Component
public class MatchAPI extends TextWebSocketHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    private  boolean secondHall = false;
    private  boolean secondGame = false;

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private Match matcher;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            User user = (User) session.getAttributes().get("user");
            if (onlineUserManager.getWebSocketSessionByUserIdInGameHall(user.getUserId()) != null
                    | onlineUserManager.getWebSocketSessionByUserIdInGameRoom(user.getUserId()) != null){

                System.out.println("检测到用户想要多开！，");
                MatchResponse response = new MatchResponse();//MatchResponse 是我们专为 WebSocket 设计的响应模型
                response.setOk(true);
                response.setReason("当前禁止多开!");
                response.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
            }

            //接下来是正常情况
            onlineUserManager.enterGameHall(user.getUserId(),session);
            System.out.println("玩家 " + user.getUsername() + " 进入游戏大厅!");
        }catch (NullPointerException e){
                MatchResponse matchResponse = new MatchResponse();
                matchResponse.setOk(false);
                matchResponse.setReason("您尚未登录! 不能进行后续匹配功能!！");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //处理客户端请求
        //首先拿到客户端 send 发送的数据
        User user = (User) session.getAttributes().get("user");
        String payload = message.getPayload();
        MatchRequest matchRequest = objectMapper.readValue(payload,MatchRequest.class);
        MatchResponse matchResponse = new MatchResponse();

        if ("startMatch".equals(matchRequest.getMessage())) {
            matcher.addUser(user);
            System.out.println("用户" + user + "加入匹配");
            matchResponse.setOk(true);
            matchResponse.setMessage("startMatch");
        } else if ( "stopMatch".equals(matchRequest.getMessage())){
            matcher.removeUser(user);
            System.out.println("用户" + user + "退出匹配");
            matchResponse.setOk(true);
            matchResponse.setMessage("stopMatch");
        }else {
            System.out.println("非法请求！");
            matchResponse.setOk(false);
            matchResponse.setReason("非法的匹配请求");
        }

        String jsonString = objectMapper.writeValueAsString(matchResponse);//将 response 对象序列化为 JSON 格式的字符串。
        session.sendMessage(new TextMessage(jsonString));//发送web给服务器
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
       try {
           //玩家下线
           User user= (User) session.getAttributes().get("user");
           //玩家下线要踢出正在游戏大厅的会话
           WebSocketSession hall = onlineUserManager.getWebSocketSessionByUserIdInGameHall(user.getUserId());

           if (session == hall){
               onlineUserManager.exitGameHall(user.getUserId());
               System.out.println("用户下线，退出匹配");
           }

           matcher.removeUser(user);
       }catch (NullPointerException e){
           System.out.println("当前用户未登录");
       }
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception{
        //当 WebSocket 连接被关闭时调用。
        try {
            //玩家下线
            User user= (User) session.getAttributes().get("user");
            //玩家下线要踢出正在游戏大厅的会话
            WebSocketSession hall = onlineUserManager.getWebSocketSessionByUserIdInGameHall(user.getUserId());

            if (session == hall){
                onlineUserManager.exitGameHall(user.getUserId());
                System.out.println("退出匹配，进入对决");
            }

            matcher.removeUser(user);
        }catch (NullPointerException e){
            System.out.println("当前用户未登录");
        }
    }
}
